package com.tianji.learning.pojo;

import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟任务
 * */
@Data
public  class DelayedTask implements Delayed {

        /**
         * 消息体
         * */
        private Object data;

        /**
         * 到期时间，毫秒
         * */
        private Long deadline;

        public DelayedTask(Object data, int expireSeconds){
            this.data = data;
            this.deadline = System.currentTimeMillis() + expireSeconds * 1000;
        }

        /**
         * 获取元素的剩余的有效期
         * */
        @Override
        public long getDelay(TimeUnit unit) {
            long remain = deadline - System.currentTimeMillis();
            if(remain <= 0){
                remain = 0;
            }
            return unit.convert(remain, TimeUnit.MILLISECONDS);
        }

        /**
         * 比较元素的剩余有效期，看谁先到期
         * */
        @Override
        public int compareTo(Delayed o) {
            long result = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
            if(result > 0){
                return 1;
            }else if(result < 0){
                return -1;
            }else{
                return 0;
            }
        }
    }